/**
 * 获取cookie
 * @param {String | Array<String>} key 获取的cookie的key 数组时返回对象
 * @returns {String | Object} 返回的cookie
 * */ 
const getCookies = (key) => {
    let cookies = document.cookie;
    let cookieArr = cookies.split(';');
    let cookieObj = {};
    for(let i = 0; i < cookieArr.length; i++){
        let item = cookieArr[i].split('=');
        cookieObj[item[0].trim()] = item[1];
    }
    if(key){
        if(Array.isArray(key)){
            let obj = {};
            key.forEach(item => {
                obj[item] = cookieObj[item];
            })
            return obj;
        }else{
            return cookieObj[key];
        }
    }
    return cookieObj;
  
}

/**
 * 设置cookie
 * @param {Object} option 配置
 * @param {String} option.key cookie的key 必填
 * @param {String} option.value cookie的value 必填
 * @param {Number} [option.expires] cookie的过期时间 默认是1
 * @param {'days' | 'hours' | 'minutes' | 'seconds'} [option.type] cookie的时间类型 默认是天 可选值 hours days minutes seconds
 * @returns {Boolean} 是否设置成功
 * */ 
const setCookie = (option) => {
    let options = {
        key : '',
        value : '',
        expires : 1,
        type : 'days'
    }
    options = {...options , ...option};
    const date = new Date();
    if(options.type == 'hours'){
        date.setTime(date.getTime() + (options.expires * 60 * 60 * 1000));
    }else if(options.type == 'days'){
        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    }else if(options.type == 'minutes'){
        date.setTime(date.getTime() + (options.expires * 60 * 1000));
    }else{
        date.setTime(date.getTime() + (options.expires * 1000));
    }
    document.cookie = `${options.key}=${options.value};expires=${date.toUTCString()};path=/`;
    return true;
}

/**
 * 删除cookie
 * @param {String | Array<String>} key 删除的cookie的key 数组时删除多个
 * @returns {Boolean} 是否删除成功
 * */ 
const removeCookie = (key) => {
    if(Array.isArray(key)){
        key.forEach(item => {
            document.cookie = `${item}=;expires=${new Date(0).toUTCString()};path=/`;
        })
    }else{
        document.cookie = `${key}=;expires=${new Date(0).toUTCString()};path=/`;
    }
    return true;
}


module.exports = {
    getCookies,
    setCookie,
    removeCookie
}